package com.itheima.service;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@SuppressWarnings("all")
public class UserService implements UserDetailsService {

    /**
     * UserDetailsService提供登录用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);

        com.itheima.health.pojo.User user = findByUsername(username);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

       Set<Role> roles = user.getRoles();

       roles.forEach(role -> {

           authorities.add(new SimpleGrantedAuthority(role.getKeyword()));

           Set<Permission> permissions = role.getPermissions();

           permissions.forEach(permission -> {

               authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
           });
       });

        User userDateils = new User(username, user.getPassword(), authorities);

        return userDateils;
    }
    private com.itheima.health.pojo.User findByUsername (String username){
        if("admin".equals(username)) {
            com.itheima.health.pojo.User user = new com.itheima.health.pojo.User();
            user.setUsername("admin");
            // 使用密文，删除{noop}
            user.setPassword("$2a$10$u/BcsUUqZNWUxdmDhbnoeeobJy6IBsL1Gn/S0dMxI2RbSgnMKJ.4a");

            // 角色
            Role role = new Role();
            role.setKeyword("ROLE_ADMIN");

            // 权限
            Permission permission = new Permission();
            permission.setKeyword("ADD_CHECKITEM");

            // 给角色添加权限
            role.getPermissions().add(permission);

            // 把角色放进集合
            Set<Role> roleList = new HashSet<Role>();
            roleList.add(role);

            role = new Role();
            role.setKeyword("ABC");
            roleList.add(role);

            /**
             * admin
             * 角色-- ROLE_ADMIN
             *      权限-- ADD_CHECKITEM
             * 角色-- ABC
             */

            // 设置用户的角色
            user.setRoles(roleList);
            return user;
        }

        return null;
    }
}
